﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TouchMove : MonoBehaviour
{
    public float speed = 1.0f; // 角色移动速度
    private Vector3 target; // 目标位置
    private bool isOver = true; // 移动是否结束

    public GameObject effice;
    float [] posvalue = new float[4];

    void Update()
    {
        if (Const.isgameover)
            return;
        if (Input.GetMouseButton(0))
        {
            GetMonsePos();
        }
        if (Input.GetMouseButtonUp(0))
        {
            effice.SetActive(false);
            MoveRecentlyPos();
        }
    }

    // 1 获取鼠标点击的位置
    public void GetMonsePos()
    {
        // a 创建射线
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);// 从摄像机发射出一条经过鼠标当前位置的射线
        // b 发射射线
        RaycastHit hitInfo = new RaycastHit();
        if (Physics.Raycast(ray, out hitInfo))
        {
            //Debug.Log("==--==" + hitInfo.collider.name);
            // 获取碰撞点位置
            if (hitInfo.collider.name.Contains("Touch"))
            {
                effice.SetActive(true);
                target = new Vector3( hitInfo.point.x,transform.position.y,transform.position.z);
                MoveTo(target);
                //target.y = 0.5f;// 地面的y坐标为0，而cube的y必须为0.5f才能看得见
                isOver = false;
            }
        }
    }

    // 2 让角色移动到目标位置
    public void MoveTo(Vector3 tar)
    {
        if (!isOver)
        {
            Vector3 v1 = tar - transform.position;
            transform.position += v1.normalized * speed * Time.deltaTime;
            // 到达目标位置
            if (Vector3.Distance(tar, transform.position) <= 0.5f)
            {
                isOver = true;
                transform.position = tar;
            }
        }
    }

    int id = 0;
    private void MoveRecentlyPos()
    {
        posvalue[0] = Mathf.Abs(this.transform.position.x - GameControl._Instance.Createpos[0].position.x);
        posvalue[1] = Mathf.Abs(this.transform.position.x - GameControl._Instance.Createpos[1].position.x);
        posvalue[2] = Mathf.Abs(this.transform.position.x - GameControl._Instance.Createpos[2].position.x);
        posvalue[3] = Mathf.Abs(this.transform.position.x - GameControl._Instance.Createpos[3].position.x);

        //Debug.Log("=====|" + this.transform.position.x);
        for (int i = 0; i < posvalue.Length; i++)
        {
            if(posvalue[id]>posvalue[i])
            {
                id = i;
            }
        }

        this.transform.position = new Vector3(GameControl._Instance.Createpos[id].position.x, this.transform.position.y, this.transform.position.z);
    }


}
